
//
//  Created by henry on 13-3-25.
//  Copyright (c) 2013年 henry. All rights reserved.
//

#import "CaogaoViewController.h"
#import "Config.h"
#import "Utility.h"
#import "GonggaoMember.h"
#import "GonggaoViewController.h"
#import "BowenMemberViewController.h"
#import "AppDelegate.h"
#import "JSON.h"
#import "DefineAction.h"
#import "MBProgressHUD.h"
#import "UIImageUIImageExt.h"
#import "CustomNavigationController.h"



@implementation CaogaoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
       
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    self.isExpandJianjie=NO;
    float height=379;
    if (iPhone5) {
        height+=88;
    }
    self.view.frame=CGRectMake(0, 0, 320, height);
     self.voiceRecord=[[VoiceRecord alloc] init];
     self.voiceRecord.delegate=self;
    [self initggTableView];
     self.takephoto=[[TakePhoto alloc] init];
     self.takephoto.delegate=self;
	// Do any additional setup after loading the view.
    
    _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.mytableView.bounds.size.height, self.view.frame.size.width, self.mytableView.bounds.size.height)];
    _refreshHeaderView.delegate = self;
    [self.mytableView addSubview:_refreshHeaderView];
    [_refreshHeaderView refreshLastUpdatedDate];
}

-(void) loadGonggaoDataFromServer:(NSDictionary*) param{
        self.caogaoDict=[NSMutableDictionary dictionaryWithDictionary:param];
        [self.ggList removeAllObjects];
        [self loadbinfoFromServer];
        self.isEndData=YES;
        self.page=1;
    }
    
-(void) loadFromServer:(int) page{
        AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
        if (app.status==NotReachable) {
            [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
            return;
        }
        NSMutableDictionary *param=[NSMutableDictionary dictionary];
        [param setObject:[self.caogaoDict objectForKey:@"str1"] forKey:@"id"];
        [param setObject:[NSString stringWithFormat:@"%d",page] forKey:@"type"];
        //NSLog(@"%@",[NSString stringWithFormat:@"%@/%@?id=%@&type=%d",[Utility  getServerUrl],GONGGAOLISTACTION,[self.caogaoDict objectForKey:@"str1"],page]);
        NSString *url=[NSString stringWithFormat:@"%@/%@",[Utility  getServerUrl],GONGGAOLISTACTION];
   
        self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:param andFile:nil];
           [[MBProgressHUD showHUDAddedTo:self.view animated:YES] setLabelText:LOADING_TITLE_DEFAULT];
        [self.request startLoadData];
    }

-(void) loadbinfoFromServer{
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
    NSString *url=[NSString stringWithFormat:@"%@/%@?id=%@&b.b0=%@",[Utility  getServerUrl],GETBINFOACTION,userId,[self.caogaoDict objectForKey:@"str1"]];
    
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:nil andFile:nil];
    [[MBProgressHUD showHUDAddedTo:self.view animated:YES] setLabelText:LOADING_TITLE_DEFAULT];
    [self.request startLoadData];

}


- (void)requestFinished:(id)context{
         self.mytableView.tableFooterView.hidden=YES;
         self.mytableView.contentInset=UIEdgeInsetsMake(0, 0,0, 0);
        [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
        @try{
            NSDictionary *result=[context JSONValue];
            if (result!=nil&&[[result  objectForKey:@"code"] integerValue]==0) {
                if ([[result objectForKey:@"method"] isEqualToString:GONGGAOLISTACTION]) {
                    NSArray *data=[result objectForKey:@"list"];
                    if (data&&(NSNull*)data!=[NSNull null]&&data.count>0) {
                        [self.ggList addObjectsFromArray:data];
                         self.isEndData=NO;
                        [self.mytableView  reloadData];
                    }else{
                        self.isEndData=YES;
                    }
                }else if ([[result objectForKey:@"method"] isEqualToString:GETBINFOACTION]){
                     [self loadFromServer:1];
                    [self.memberList removeAllObjects];
                    [self.memberList addObjectsFromArray:[result objectForKey:@"list"]];
                }
                
            }else{
                [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
            }
        }@catch (NSException *e) {
            [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        }
        [self doneLoadingTableViewData];
    }
    
    - (void)requestFailed:(id)context error:(NSString *)error{
         self.mytableView.tableFooterView.hidden=YES;
         self.mytableView.contentInset=UIEdgeInsetsMake(0, 0,0, 0);
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:NO];
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
    }



-(void) initggTableView{
    
    
    self.mytableView=[[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.mytableView.delegate=self;
    self.mytableView.dataSource=self;
    //self.mytableView.showsVerticalScrollIndicator=NO;
    self.mytableView.separatorStyle=UITableViewCellEditingStyleNone;
    [self.view addSubview:self.mytableView];
    self.ggList=[NSMutableArray array];
    self.memberList=[NSMutableArray array];
    [self initPopMenu];
    [self initFootLoadingMore];
}

-(void) initFootLoadingMore{
    UIView *footView=[[UIView alloc] initWithFrame:CGRectMake(0,  0, self.view.frame.size.width, 30)];
    footView.tag=FOOTVIEWTAG;
    footView.backgroundColor=[UIColor  clearColor];
    UIActivityIndicatorView *activityIndicatorView=[[UIActivityIndicatorView alloc]
                                                    initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicatorView.frame=CGRectMake(100, 5, 20, 20);
    [activityIndicatorView startAnimating];
    
    [footView addSubview:activityIndicatorView];
    // [activityIndicatorView release];
    UILabel *moreLabel=[[UILabel alloc] initWithFrame:CGRectMake(135, 5, 110, 20)];
    moreLabel.backgroundColor=[UIColor clearColor];
    moreLabel.textColor=[UIColor blackColor];
    moreLabel.font=[UIFont fontWithName:FONT_FAMILY size:12.0f];
    moreLabel.text=LOADING_TITLE_DEFAULT;
    [footView addSubview:moreLabel];
    self.mytableView.tableFooterView=footView;
    self.mytableView.tableFooterView.hidden=YES;
    [self tableViewHeader];
}

-(void) initPopMenu{
    
    UIView *popView =[[UIView alloc] initWithFrame:CGRectZero];
    popView.backgroundColor=[UIColor clearColor];
    popView.tag=POPMENUTAG;
    popView.hidden=YES;
    
    UILabel *labelIndex=[[UILabel alloc] initWithFrame:CGRectZero];
    labelIndex.tag=POPBUTTONTAG+5;
    labelIndex.text=@"0";
    labelIndex.hidden=YES;
    [popView addSubview:labelIndex];
    
    UIButton *button1=[Utility customButton:self action:@selector(onclickMenuAction:) normalImage:@"cg_write_normal.png" lightedImage:@"cg_write_hover.png" frame:CGRectMake(43, 0, 43, 43) title:nil tag:POPBUTTONTAG+1];
    [popView addSubview:button1];
    
    UIButton *button2=[Utility customButton:self action:@selector(onclickMenuAction:) normalImage:@"cg_camera_normal.png" lightedImage:@"cg_camera_hover.png" frame:CGRectMake(102, 0, 43, 43) title:nil tag:POPBUTTONTAG+2];
    [popView addSubview:button2];
    UIButton *button3=[Utility customButton:self action:@selector(onclickMenuAction:) normalImage:@"cg_photo_normal.png" lightedImage:@"cg_photo_hover.png" frame:CGRectMake(160, 0, 43, 43) title:nil tag:POPBUTTONTAG+3];
    [popView addSubview:button3];
    
    UIButton *button4=[Utility customButton:self action:@selector(onclickMenuAction:) normalImage:@"cg_voice_normal.png" lightedImage:@"cg_voice_hover.png" frame:CGRectMake(220, 0, 43, 43) title:nil tag:POPBUTTONTAG+4];
    [popView addSubview:button4];
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressBtn:)];
    [longPressGesture setDelegate:self];
    longPressGesture.minimumPressDuration=0.3;//默认0.5秒
    [button4 addGestureRecognizer:longPressGesture];
    [self.mytableView addSubview:popView];
}

-(void) tableViewHeader{
    //表格第一行背景
    UIView *headView=[[UIView alloc] initWithFrame:CGRectZero];
    headView.userInteractionEnabled=YES;
    //顶部背景
    UIImageView *topBackground=[[UIImageView alloc] initWithFrame:CGRectZero];
    topBackground.tag=100;
    topBackground.userInteractionEnabled=YES;
    UIImage *image=[Utility imageNamed:@"cg_bg1.png"];
    UIEdgeInsets insets=UIEdgeInsetsMake(22, 0, 23, 0);
    if ([[[UIDevice currentDevice] systemVersion] floatValue]<6.0) {
        image=[image resizableImageWithCapInsets:insets];
    }else{
        image=[image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    }
    topBackground.image=image;
    //博文标题
    UILabel *labelTile=[Utility detailTextLabel:CGRectMake(10, 10, 200, 20) andFontSize:15.0];
    labelTile.tag=101;
    labelTile.textColor=UIColorFromRGB(0x000000);
    [topBackground addSubview:labelTile];
    
   //博文标题所属圈子
    UILabel *labelanthor=[Utility detailTextLabel:CGRectZero andFontSize:12];
    labelanthor.textColor=UIColorFromRGB(0x6e6e6e);
    labelanthor.tag=102;
    [topBackground addSubview:labelanthor];
    
    //当圈子的简介非空是显示查看收起简介按钮
    [topBackground addSubview:[Utility customButton:self action:@selector(floderHidenJianjieAction:) normalImage:@"jianjie_open_normal.png" lightedImage:@"jianjie_close_normal.png" frame:CGRectMake(230,5,77,33) title:nil tag:103]];
    [headView addSubview:topBackground];
    
    //博文简介
    UILabel *labelqzjianjie=[Utility detailTextLabel:CGRectZero andFontSize:12];
    labelqzjianjie.textColor=UIColorFromRGB(0x000000);
    labelqzjianjie.tag=104;
    [topBackground addSubview:labelqzjianjie];
    
    //参加此不问的人员滚动列表
    UIView *bottumView=[[UIView alloc] initWithFrame:CGRectZero];
    bottumView.tag=200;
    bottumView.backgroundColor=[UIColor colorWithPatternImage:[Utility imageNamed:@"cg_bg2.png"]];
    bottumView.userInteractionEnabled=YES;
    UILabel *personsLabel=[Utility detailTextLabel:CGRectMake(10, 10, 200, 18) andFontSize:12.5f];
    personsLabel.textColor=UIColorFromRGB(0x666666);
    personsLabel.tag=201;
    [bottumView addSubview:personsLabel];
    
    //滚动视图
    GonggaoMember *gonggaoMember=[[GonggaoMember alloc] initWithFrame:CGRectMake(0, 25, self.view.frame.size.width, 80)];
    gonggaoMember.delegate=self;
    gonggaoMember.tag=202;
    [bottumView insertSubview:gonggaoMember aboveSubview:bottumView];
    [headView addSubview:bottumView];
    self.row0OfTableView=headView;
}

-(IBAction)floderHidenJianjieAction:(UIButton*)sender{
    if (sender.selected) {
        sender.selected=NO;
        sender.highlighted=NO;
    }else{
        sender.selected=YES;
        sender.highlighted=YES;
    }
    UIView *popView=[self.mytableView viewWithTag:POPMENUTAG];
    popView.hidden=YES;
    self.isExpandJianjie=!self.isExpandJianjie;
    [self.mytableView reloadData];
}

-(void) showData:(BOOL) status{
    UIImageView *topBackground=(UIImageView*)[self.row0OfTableView viewWithTag:100];
    UILabel *labelTile=(UILabel*)[self.row0OfTableView viewWithTag:101];
    labelTile.text=[self.caogaoDict objectForKey:@"str2"];
    
    UILabel *labelanthor=(UILabel*)[self.row0OfTableView viewWithTag:102];
      UIButton *showJianjieButton=(UIButton*)[self.row0OfTableView viewWithTag:103];
    NSString *jianjie=[self.caogaoDict objectForKey:@"str6"];
    UILabel *labelqzjianjie=(UILabel*)[self.row0OfTableView viewWithTag:104];
    float padHeight=0.0f;
    if (jianjie.length>0) {
        showJianjieButton.hidden=NO;
        if (status) {
            labelanthor.hidden=NO;
            labelanthor.frame=CGRectMake(10, 38, 150, 14);
            labelanthor.textAlignment=NSTextAlignmentLeft;
            labelqzjianjie.hidden=NO;
            CGSize size=[Utility getStringSize:jianjie font:[UIFont fontWithName:FONT_FAMILY size:12] withMaxSize:CGSizeMake(300, 100)];
            labelqzjianjie.numberOfLines=size.height/17;
            labelqzjianjie.frame=CGRectMake(10, 64, 300, size.height);
            labelqzjianjie.text=jianjie;
            padHeight=20;
        }else{
            labelanthor.hidden=NO;
            labelqzjianjie.hidden=YES;
            labelanthor.frame=CGRectMake(10, 43, 0,0);
            labelqzjianjie.frame=CGRectMake(10, 43, 0,0);
        }
    }else{
        showJianjieButton.hidden=YES;
        labelanthor.frame=CGRectMake(160, 12, 150, 14);
        labelanthor.textAlignment=NSTextAlignmentRight;
        labelqzjianjie.hidden=YES;
         labelqzjianjie.frame=CGRectMake(10, 43, 0,0);
    }
  labelanthor.text=[NSString  stringWithFormat:@"圈子：%@",[self.caogaoDict objectForKey:@"str8"]];
    topBackground.frame=CGRectMake(0, 0, 320,labelqzjianjie.frame.origin.y+labelqzjianjie.frame.size.height+padHeight);
    UIView *bottumView=[self.row0OfTableView viewWithTag:200];
    bottumView.frame=CGRectMake(0, topBackground.frame.origin.y+topBackground.frame.size.height, 320, 119);
    UILabel *personsLabel=(UILabel*)[self.row0OfTableView viewWithTag:201];
    personsLabel.text=[NSString stringWithFormat:@"%d人一起为本文供稿",[self.memberList count]];
    GonggaoMember *gonggaoMember=(GonggaoMember*)[self.row0OfTableView viewWithTag:202];
    [gonggaoMember showData:self.memberList];
    
    self.row0OfTableView.frame=CGRectMake(0, 0, 320, bottumView.frame.size.height+bottumView.frame.origin.y);

}


#pragma -mark GonggaoMemberDelegate
-(void) onclickPersinalButton:(NSString*)personId{
    NSLog(@"个人ID＝%@",personId);
    BowenMemberViewController *bowenMemberViewController=[[BowenMemberViewController alloc] initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:bowenMemberViewController animated:YES];
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.ggList count]+2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        return cell.frame.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row==0) {
        static NSString *cellIdentity0 = @"caogaoViewCell0";
        
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellIdentity0];
        if (cell ==  nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity0];
        }
        for (UIView *view in cell.subviews) {
            [view removeFromSuperview];
        }
        [self showData:self.isExpandJianjie];
        [cell addSubview:self.row0OfTableView];
        cell.frame=self.row0OfTableView.frame;
        if (self.ggList.count==0) {
        UIButton *popButtonbutton=[Utility customButton:self action:@selector(showMenuCell0Action:) normalImage:@"cg_menubutton_normal.png" lightedImage:@"cg_menubutton_hover.png" frame:CGRectMake(270, cell.frame.size.height-23, 43, 43) title:nil tag:0];
        [cell addSubview:popButtonbutton];
         }
         cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;

    }else if(indexPath.row==self.ggList.count+1){
        static NSString *cellIdentity1 = @"caogaoViewCell1";
        
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellIdentity1];
        if (cell ==  nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity1];
        }
            for (UIView *view in cell.subviews) {
                [view removeFromSuperview];
            }
             cell.selectionStyle=UITableViewCellSelectionStyleNone;
         cell.frame=CGRectMake(0, 0, 320, 43.0f);
             [cell addSubview:[Utility customButton:self action:@selector(showMenuBottom:) normalImage:@"cg_menubutton_normal.png" lightedImage:@"cg_menubutton_hover.png" frame:CGRectMake(270, -23, 43, 43) title:nil tag:111]];
        return cell;
    }else{
        static NSString *cellIdentity = @"caogaoViewCell";
        
        CaogaoViewCell *cell = (CaogaoViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentity];
        if (cell ==  nil) {
            cell = [[CaogaoViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity];
        }
        cell.delegate=self;
        cell.row=indexPath.row;
        NSDictionary *dict=[self.ggList objectAtIndex:indexPath.row-1];
         cell.contentText.hidden=YES;
         cell.eMAsyncImageView.hidden=YES;
         cell.voiceButton.hidden=YES;
        switch ([[dict objectForKey:@"count2"] integerValue]) {
            case 1:{//文本
                cell.contentText.hidden=NO;
                UIFont *font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
                CGSize size=[Utility getStringSize:[dict objectForKey:@"str5"] font:font withMaxSize:CGSizeMake(300, 100)];
                if (size.height>=60) {
                    cell.contentText.numberOfLines=3;
                    [cell setFrame:CGRectMake(0, 0, 320, 100)];
                }else{
                    cell.contentText.numberOfLines=(size.height/20);
                    [cell setFrame:CGRectMake(0, 0, 320, size.height+40)];
                }
                
                if (size.height>=60) {
                    cell.contentText.frame=CGRectMake(10, 12, 300, 60);
                }else{
                    cell.contentText.frame=CGRectMake(10, 12, 300, size.height);
                }
                cell.contentText.text=[dict objectForKey:@"str5"];
                cell.detailText.frame=CGRectMake(10, cell.contentText.frame.size.height+16, 150, 12);
                cell.statusImage.frame=CGRectMake(220, cell.contentText.frame.size.height+15, 29, 14);
                cell.detailText.text=[NSString stringWithFormat:@"阅读: %@  评论: %@",[dict objectForKey:@"count6"],[dict objectForKey:@"count5"]];
                break;
            }
            case 2:{//图片
                cell.eMAsyncImageView.hidden=NO;
                cell.eMAsyncImageView.imageUrl=[NSString stringWithFormat:@"%@/%@?id=%@&type=1",[Utility  getServerUrl],DOWNFILEACTION,[dict objectForKey:@"str1"]];
                cell.eMAsyncImageView.frame=CGRectMake(10,12,100,100);
                cell.eMAsyncImageView.imageId=[dict objectForKey:@"str1"];
        
                cell.detailText.frame=CGRectMake(10, cell.eMAsyncImageView.frame.size.height+16, 150, 12);
                cell.statusImage.frame=CGRectMake(220, cell.contentText.frame.size.height+15, 29, 14);
                cell.detailText.text=[NSString stringWithFormat:@"阅读: %@  评论: %@",[dict objectForKey:@"count6"],[dict objectForKey:@"count5"]];
                
                [cell setFrame:CGRectMake(0, 0, 320, cell.eMAsyncImageView.frame.size.height+40)];
                break;
            }
            case 3:{//语音
                cell.voiceButton.hidden=NO;
                cell.voiceButton.frame=CGRectMake(10, 12, 38, 38);
                [cell.voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateNormal];
                 [cell.voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateSelected];
                [cell.voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateHighlighted];
                cell.voiceButton.tag=indexPath.row;
                [cell.voiceButton addTarget:self action:@selector(playmp3Action:) forControlEvents:UIControlEventTouchUpInside];
                cell.detailText.frame=CGRectMake(10, cell.voiceButton.frame.size.height+21, 150, 12);
                cell.statusImage.frame=CGRectMake(220, cell.contentText.frame.size.height+20, 29, 14);
                cell.detailText.text=[NSString stringWithFormat:@"阅读: %@  评论: %@",[dict objectForKey:@"count6"],[dict objectForKey:@"count5"]];
                
                [cell setFrame:CGRectMake(0, 0, 320, cell.voiceButton.frame.size.height+40)];
                break;
            }
            case 4:{//视频
                
                break;
            }
        }
        
        if (indexPath.row==1) {
            cell.popButtontop.hidden=YES;
        }else{
            cell.popButtontop.hidden=NO;
            cell.popButtontop.frame=CGRectMake(270, -23, 43, 43);
        }
        cell.popButtonbutton.frame=CGRectMake(270, cell.frame.size.height-23, 43, 43);
         cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        return cell;
    }
   
    }
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row>0&&indexPath.row<self.ggList.count+1) {
        GonggaoViewController *ggv=[[GonggaoViewController alloc] initWithNibName:nil bundle:nil];
        ggv.gonggaoDict=[self.ggList objectAtIndex:indexPath.row-1];
        [ggv loadPinglunFromServer:1];
        [self.navigationController pushViewController:ggv animated:YES];
    }
}

//第一个cell的点击事件
-(void) showMenuBottom:(id) sender{
    [self showMenu:(self.ggList.count)];
}

//第一个cell的点击事件
-(void) showMenuCell0Action:(UIButton*) sender{
    [self showMenu:0];
}
-(void) showMenu:(int) row{
    if (row<0) {
        row=0;
    }
    NSIndexPath *indexPathtemp=[NSIndexPath  indexPathForRow:row inSection:0];
    CGRect rect=[self.mytableView rectForRowAtIndexPath:indexPathtemp];
    UIView *popView=[self.mytableView viewWithTag:POPMENUTAG];
     UILabel *labelIndex=(UILabel*)[self.mytableView viewWithTag:POPBUTTONTAG+5];
    labelIndex.text=[NSString stringWithFormat:@"%d",row];
    popView.hidden=NO;
    popView.frame=CGRectMake(0,rect.origin.y+rect.size.height-22, 260, 43);
}

-(void) onclickMenuAction:(UIButton*) sender{
     UILabel *labelIndex=(UILabel*)[self.mytableView viewWithTag:POPBUTTONTAG+5];
    switch (sender.tag) {
        case POPBUTTONTAG+1:{
            AddGonggaoViewController *add=[[AddGonggaoViewController alloc] initWithNibName:nil bundle:nil];
            NSMutableDictionary *param=[NSMutableDictionary dictionaryWithDictionary:self.caogaoDict];
            NSInteger row=[labelIndex.text integerValue];
            if (row==0) {
                [param setObject:@"" forKey:@"preQuanziId"];
            }else{
                NSDictionary *dict=[self.ggList objectAtIndex:row-1];
                 [param setObject:[dict objectForKey:@"str1"] forKey:@"preQuanziId"];
                //NSLog(@"%@－－%@",labelIndex.text,[dict objectForKey:@"g0"]);
            }
            add.caogaoDict=param;
            add.delegate=self;
            [add topRow];
            CustomNavigationController *nav=[[CustomNavigationController alloc] initWithRootViewController:add];
            [self presentViewController:nav animated:YES completion:nil];
            break;
        }
        case POPBUTTONTAG+2:{
            NSInteger row=[labelIndex.text integerValue];
            if (row==0) {
                [self.caogaoDict setObject:@"" forKey:@"preQuanziId"];
            }else{
                NSDictionary *dict=[self.ggList objectAtIndex:row-1];
                [self.caogaoDict setObject:[dict objectForKey:@"str1"] forKey:@"preQuanziId"];
            }
            [_takephoto setupCamera:self];
            break;
        }
        case POPBUTTONTAG+3:{
            NSInteger row=[labelIndex.text integerValue];
            if (row==0) {
                [self.caogaoDict setObject:@"" forKey:@"preQuanziId"];
            }else{
                NSDictionary *dict=[self.ggList objectAtIndex:row-1];
                [self.caogaoDict setObject:[dict objectForKey:@"str1"] forKey:@"preQuanziId"];
            }
                [_takephoto setupLibrary:self];
            break;
        }
        case POPBUTTONTAG+4:{
            NSLog(@"%@",@"语音");
            break;
        }
       
    }
    
   
}
#pragma -mark camera delegate
-(void) didTakePicture:(NSData *) rawData{
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    UIImage *rawImage=[[UIImage imageWithData:rawData] imageByScalingAndCroppingForSize:CGSizeMake(600, 800)];
    NSData *imgData = UIImageJPEGRepresentation(rawImage,0.8);
    dispatch_queue_t newThread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    __weak id selfweak=self;
    dispatch_async(newThread, ^{
            __strong CaogaoViewController *selfstrong=selfweak;
            NSDictionary *result=[selfstrong uploadFile:imgData andFile:[NSMutableDictionary dictionaryWithDictionary:@{@"flydyUpload.png":imgData}]];
            if ([[result objectForKey:@"code"] integerValue]==0) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [selfstrong.mytableView reloadData];
                });
            }
    });
    
    
}

-(NSDictionary*) uploadFile:(NSData*)imgData andFile:(NSMutableDictionary*)fileparam{
    NSString *url=[NSString stringWithFormat:@"%@/%@",[Utility getServerUrl],ADDGONGGAOACTION];
    NSMutableDictionary *param=[NSMutableDictionary dictionary];
    NSString *preQuanziId=[self.caogaoDict objectForKey:@"preQuanziId"]
    ;
    NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
    if (preQuanziId!=nil&&![preQuanziId isEqual:@""]) {
        [param setObject:preQuanziId forKey:@"id"];//
    }
    for (NSString *key in fileparam.allKeys) {
        if ([key hasSuffix:@"mp3"]) {
            [param setObject:@"3" forKey:@"g.t0"];//供稿类型
        }else{
            [param setObject:@"2" forKey:@"g.t0"];//供稿类型
        }
        break;
    }
    
    [param setObject:@"" forKey:@"g.g2"];//供稿内容
    [param setObject:userId forKey:@"g.u0"];//供稿人
    [param setObject:[self.caogaoDict objectForKey:@"str1"] forKey:@"g.b0"];//草稿ID
    [param setObject:[self.caogaoDict objectForKey:@"str7"] forKey:@"g.e0"];//圈子ID
    NSMutableDictionary *result=[[URLRequest alloc] postWithUrl:url fileds:param andFile:fileparam];
    return result;
}

-(void)longPressBtn:(UILongPressGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer state]==UIGestureRecognizerStateBegan){//长按事件开始
        UIView *viewDailag=[self.view viewWithTag:90001];
        viewDailag.backgroundColor=[UIColor colorWithPatternImage:[Utility imageNamed:@"dialogButton_pressed.png"]];
        NSLog(@"开始");
        [self.voiceRecord recordBtnClick:@"0"];
        
        
    }else if([gestureRecognizer state]==UIGestureRecognizerStateEnded){//长按事件
        UIView *viewDailag=[self.view viewWithTag:90001];
        viewDailag.backgroundColor=[UIColor colorWithPatternImage:[Utility imageNamed:@"dialogButton.png"]];
        [self.voiceRecord recordBtnClick:@"0"];
        NSLog(@"结束");
    }
}

#pragma -mark VoiceRecordDelegate
-(void) convertTomp3Success:(NSString*)fileUrl{
    UILabel *labelIndex=(UILabel*)[self.mytableView viewWithTag:POPBUTTONTAG+5];
    NSInteger row=[labelIndex.text integerValue]-1;
    if (row<0||row>self.ggList.count-1) {
        [self.caogaoDict setObject:@"" forKey:@"preQuanziId"];
    }else{
        NSDictionary *dict=[self.ggList objectAtIndex:row];
        [self.caogaoDict setObject:[dict objectForKey:@"str1"] forKey:@"preQuanziId"];
    }
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    NSURL *url=[NSURL fileURLWithPath:fileUrl];
    NSData *mp3Data =[NSData  dataWithContentsOfURL:url];
    dispatch_queue_t newThread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    __weak id selfweak=self;
    dispatch_async(newThread, ^{
        __strong CaogaoViewController *selfstrong=selfweak;
        NSDictionary *result=[selfstrong uploadFile:mp3Data andFile:[NSMutableDictionary dictionaryWithDictionary:@{@"flydyUpload.mp3":mp3Data}]];
        if ([[result objectForKey:@"code"] integerValue]==0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [selfstrong.mytableView reloadData];
            });
        }
    });

}


#pragma -mark AddGonggaoViewControllerDelegate
-(void) success:(NSDictionary*)param{
     UILabel *labelIndex=(UILabel*)[self.mytableView viewWithTag:POPBUTTONTAG+5];
    NSMutableDictionary *dict=[NSMutableDictionary dictionary];
    dict[@"str1"]=[param objectForKey:@"g0"];
    dict[@"str2"]=[param objectForKey:@"u0"];
    dict[@"str3"]=[param objectForKey:@"e0"];
    dict[@"str5"]=[param objectForKey:@"g2"];
    dict[@"count1"]=[param objectForKey:@"count0"];
    dict[@"count2"]=@"1";
    dict[@"count5"]=[param objectForKey:@"count2"];
    dict[@"count6"]=[param objectForKey:@"count3"];
    dict[@"dat2"]=[param objectForKey:@"g7"];
     [self.ggList insertObject:dict atIndex:[labelIndex.text integerValue]];
     [self.mytableView  reloadData];
    self.isEndData=NO;
    UIView *popView=[self.mytableView viewWithTag:POPMENUTAG];
    popView.hidden=YES;
    [self dismissViewControllerAnimated:YES completion:nil];
   
}

// 在iOS6下已废弃
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return interfaceOrientation==UIInterfaceOrientationPortrait;
}


// Only on iOS6
- (BOOL)shouldAutorotate
{
    return NO;
}
// Only on iOS6
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

-(IBAction)playmp3Action:(UIButton*)sender{
    voiceLoading=[[UIView alloc] initWithFrame:sender.frame];
    voiceLoading.backgroundColor=[UIColor colorWithRed:249.0/255 green:249.0/255 blue:249.0/255 alpha:1.0];
    UIActivityIndicatorView *activityIndicatorView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicatorView.center=CGPointMake((sender.frame.size.width-20)/2, (sender.frame.size.height-30)/2);
    [activityIndicatorView startAnimating];
    [voiceLoading addSubview:activityIndicatorView];
    [sender  addSubview:voiceLoading];
    
     NSDictionary *dict=[self.ggList objectAtIndex:[sender tag]-1];
   NSString *url=[NSString stringWithFormat:@"%@/%@?id=%@&type=2",[Utility  getServerUrl],DOWNFILEACTION,[dict objectForKey:@"str1"]];
    EMAsyncFile *eMAsyncFile=[[EMAsyncFile alloc] init];
    eMAsyncFile.imageIdKey=@"id";
    eMAsyncFile.delegate=self;
    [eMAsyncFile setImageUrl:url];
   
}
#pragma -mark EMAsyncFileDelegate
-(void) fileSuccess:(NSString*)url{
    [voiceLoading removeFromSuperview];
    self.voiceRecord=[[VoiceRecord alloc] init];
    self.voiceRecord.delegate=self;
    [self.voiceRecord playMp3Click:url];
    
}
-(void) fileFail:(NSString*)error{
    [voiceLoading removeFromSuperview];

}

-(void)reloadTableViewDataSource{
    _reloading = YES;
    [self loadGonggaoDataFromServer:self.caogaoDict];
    [self.mytableView reloadData];
    
    
    
}
- (void)doneLoadingTableViewData{
    //  model should call this when its done loading
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.mytableView];
    
    
}
#pragma mark –
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    UIView *popView=[self.mytableView viewWithTag:POPMENUTAG];
    popView.hidden=YES;
     [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    UIView *view=[self.view  viewWithTag:FOOTVIEWTAG];
    if (!self.isEndData&&scrollView.contentOffset.y+self.mytableView.frame.size.height-view.frame.size.height>=self.mytableView.contentSize.height) {
        self.mytableView.contentInset=UIEdgeInsetsMake(0, 0, view.frame.size.height, 0);
        self.mytableView.tableFooterView.hidden=NO;
        if (self.ggList.count>0) {
            [self loadFromServer:self.page+1];
        }
        
    }else{
      [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}


#pragma mark –
#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
    [self reloadTableViewDataSource];
    
    
    
}
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    
    return _reloading; // should return if data source model is reloading
    
}
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    
    return [NSDate date]; // should return date data source was last changed
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
